package com.leyou.search.service.impl;


import com.leyou.dto.PageDTO;
import com.leyou.item.clients.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.pojo.vo.SpuVo;

import com.leyou.search.entity.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.IndexService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author ：qcq
 * @date ：Created in 2020/12/12 19:39
 * @description：
 */
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private GoodsRepository goodsRepository;

    @Override
    public void loadData() {


        deleteAndCreateIndex();
        Integer page = 1;
        while (true) {
            PageDTO<SpuDTO> pageDTO = this.itemClient.findPage(page,40,true,null,null,null);
            List<Goods> goodsList = pageDTO.getItems().stream().map(this::buildGoods).collect(Collectors.toList());
            goodsRepository.saveAll(goodsList);
            ++page;
            System.out.println(pageDTO.getTotalPage());
            if (pageDTO.getTotalPage() < page) {
                break;
            }

        }
    }

    private void deleteAndCreateIndex() {
        goodsRepository.deleteIndex();

        this.goodsRepository.createIndex("{\n" +
                "  \"settings\": {\n" +
                "    \"analysis\": {\n" +
                "      \"analyzer\": {\n" +
                "        \"my_pinyin\": {\n" +
                "          \"tokenizer\": \"ik_smart\",\n" +
                "          \"filter\": [\n" +
                "            \"py\"\n" +
                "          ]\n" +
                "        }\n" +
                "      },\n" +
                "      \"filter\": {\n" +
                "        \"py\": {\n" +
                "\t\t  \"type\": \"pinyin\",\n" +
                "          \"keep_full_pinyin\": true,\n" +
                "          \"keep_joined_full_pinyin\": true,\n" +
                "          \"keep_original\": true,\n" +
                "          \"limit_first_letter_length\": 16,\n" +
                "          \"remove_duplicated_term\": true\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  },\n" +
                "  \"mappings\": {\n" +
                "    \"properties\": {\n" +
                "      \"id\": {\n" +
                "        \"type\": \"keyword\"\n" +
                "      },\n" +
                "      \"suggestion\": {\n" +
                "        \"type\": \"completion\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"title\":{\n" +
                "        \"type\": \"text\",\n" +
                "        \"analyzer\": \"my_pinyin\",\n" +
                "        \"search_analyzer\": \"ik_smart\"\n" +
                "      },\n" +
                "      \"image\":{\n" +
                "        \"type\": \"keyword\",\n" +
                "        \"index\": false\n" +
                "      },\n" +
                "      \"updateTime\":{\n" +
                "        \"type\": \"date\"\n" +
                "      },\n" +
                "      \"specs\":{\n" +
                "        \"type\": \"nested\",\n" +
                "        \"properties\": {\n" +
                "          \"name\":{\"type\": \"keyword\" },\n" +
                "          \"value\":{\"type\": \"keyword\" }\n" +
                "        }\n" +
                "      }\n" +
                "    }\n" +
                "  }\n" +
                "}");
    }

    @Override
    public Goods buildGoods(SpuDTO spuDTO)  {
        Goods goods = new Goods();
        BeanUtils.copyProperties(spuDTO, goods);

        //categoryId
        Long categoryId = spuDTO.getCid3();
        goods.setCategoryId(categoryId);
        //suggestion 候选值，主体名称，品牌+主体,品牌+分类，分类+品牌

        ArrayList<String> suggestList = new ArrayList<>();
        String goodsName = spuDTO.getName();
        String brandName =  StringUtils.substringBefore(spuDTO.getBrandName(), "（");
        String categoryName = StringUtils.substringAfterLast(spuDTO.getCategoryName(),"/");

        suggestList.add(goodsName);
        suggestList.add(brandName + goodsName);
        suggestList.add(brandName + categoryName);
        suggestList.add(categoryName + categoryName);

        goods.setSuggestion(suggestList);

        String title = goodsName + "" + brandName + "" + categoryName;
        goods.setTitle(title);

        //以下是sku中数据
        Set<Long> prices = new HashSet<>();
        Long sold = 0L;
        Long spuId = spuDTO.getId();
        List<SkuDTO> skuDTOS = itemClient.querySkuBySpuId(spuId);
        for (SkuDTO skuDTO : skuDTOS) {
            prices.add(skuDTO.getPrice());
            sold = sold + skuDTO.getSold();
        }
        goods.setPrices(prices);
        goods.setSold(sold);

        goods.setImage(StringUtils.substringBefore(skuDTOS.get(0).getImages(),","));

        List<HashMap<String, Object>> specs = this.itemClient.listSpec(spuDTO.getId(), true).stream()
                .map(specParamDTO -> {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("name", specParamDTO.getName());
                    map.put("value", chooseSegment(specParamDTO));
                    return map;
                }).collect(Collectors.toList());
        goods.setSpecs(specs);

        goods.setUpdateTime(new Date());

        return goods;
    }

    private Object chooseSegment(SpecParamDTO p) {
        Object value = p.getValue();
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        if (!p.getNumeric() || StringUtils.isBlank(p.getSegments()) || value instanceof Collection) {
            return value;
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }
}
